<template>
    <div>
    <div>
<el-form :model="search" style=" margin: 20px 0 0 20px;" ref="search" label-width="100px">
  <el-row>
    <el-col :span="4" style=" margin-right: 20px;">
      <el-form-item label="货品类型">
        <el-input v-model="search.Key" placeholder="请输入货品类型名称/编号" style="width: 100%;"/>
      </el-form-item>
    </el-col>
    <el-col :span="4">
      <el-form-item label="状态">
        <el-select v-model="search.Status" placeholder="请选择" style="width: 100%;">
          <el-option label="启用" value="true"></el-option>
          <el-option label="停用" value="false"></el-option>
        </el-select>
      </el-form-item>
    </el-col>
    <el-col :span="4" style=" margin-right: 20px;">
      <el-form-item label="操作人">
        <el-input v-model="search.Operator" placeholder="请输入" style="width: 100%;"/>
      </el-form-item>
    </el-col>
    <!-- <el-col :span="4" style=" margin-right: 20px;">
      <el-form-item label="操作时间">
        <el-input v-model="search.OperationTime" placeholder="请输入" style="width: 100%;"/>
      </el-form-item>
    </el-col> -->
    <el-col :span="4" style="margin-right: 20px;">
  <el-form-item label="操作时间">
    <el-date-picker
      v-model="search.OperationTime"
      type="datetime"
      placeholder="请选择时间"
      style="width: 100%;"
    />
  </el-form-item>
</el-col>
    <el-col :span="2">
      <el-button class="cz" type="primary" @click="clear()">重置</el-button>
    </el-col>
    <el-col :span="2">
      <el-button class="cx" type="primary" @click="query()">查询</el-button>
    </el-col>
  </el-row>
</el-form>
</div>
<div><el-button class="cx" type="primary" style="margin-left:20px;" @click="add()">新增</el-button></div>
<div id="dataDiv">
      <el-table :data="data" class="bian">
        <el-table-column label="序号" prop="p_ProductTypeId"></el-table-column>
        <el-table-column label="货品类型编号" prop="p_ProductTypeCode"></el-table-column>
        <el-table-column label="货品类型名称" prop="p_ProductTypeName"></el-table-column>
        <el-table-column label="排序" prop="p_ProductTypeSorting"></el-table-column>
        <el-table-column label="状态" prop="p_ProductTypeStatus" :formatter="formatStatus"></el-table-column>
        <el-table-column label="备注" prop="p_ProductTypeDescr"></el-table-column>
        <el-table-column label="操作人" prop="p_ProductTypeOperator"></el-table-column>
        <el-table-column label="操作时间" prop="p_ProductTypeOperationTime"></el-table-column>
        <el-table-column label="逻辑删除" prop="p_PIsDelete" v-if="showIdInput"></el-table-column>
        <el-table-column label="父编号" prop="p_ProductTypePid" v-if="showIdInput"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="text" @click="upd(scope.row)">编辑</el-button>
            <el-button type="text" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        </el-table>
        <el-pagination v-on:size-change="handleSizeChange"
			   v-on:current-change="handleCurrentChange"
			   :current-page="currentPage"
			   :page-sizes="[2, 4, 5, 6]"
			   :page-size="pageSize"
			   layout="total, sizes, prev, pager, next, jumper">
</el-pagination>
    </div>
      <!-- 模态框部分 -->
    <!-- 添加页面 -->
  <el-dialog title="新增" :visible.sync="insert" width="50%">
  <el-form :model="insertAdd" ref="insertFrom" label-width="100px">
  <el-row>
  <el-col :span="12" class="xi">
      <el-form-item label="上级分类">
        <el-cascader v-model="insertAdd.SjType"
        :options="options"
        :props="{ checkStrictly:true }"
        v-on:change="handleCascaderChange">
      </el-cascader>
      </el-form-item>
      </el-col>
      <el-col :span="12">
        <span class="xin">*</span><el-form-item label="货品类型编号" prop="Code">
          <el-input v-model="insertAdd.Code" placeholder="自动获取系统编号" disabled readonly></el-input>
        </el-form-item>
    </el-col>
  </el-row>
    <el-row>
      <el-col :span="12">
        <span class="xin">*</span><el-form-item label="货品类型名称" prop="Name">
          <el-input v-model="insertAdd.Name"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12" class="xinx">
        <el-form-item label="排序" prop="Sort">
          <el-input v-model="insertAdd.Sort"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
<el-col :span="12">
  <el-form-item label="状态" prop="Status">
    <el-radio-group v-model="insertAdd.Status">
      <el-radio :label="true">启用</el-radio>
      <el-radio :label="false">停用</el-radio>
    </el-radio-group>
  </el-form-item>
</el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="备注" prop="Remarks">
          <el-input type="textarea" v-model="insertAdd.Remarks" :rows="4"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row justify="end">
      <el-col>
        <el-button class="cz" @click="cancel()">取消</el-button>
        <el-button class="cx" @click="addFrom('insertFrom')">保存</el-button>
      </el-col>
    </el-row>
  </el-form>
</el-dialog>
<!-- 修改页面-->
  <el-dialog title="编辑" :visible.sync="uinsert" width="50%">
  <el-form :model="insertUpd" ref="insertFrom" label-width="100px">
   <el-row v-if="showIdInput">
  <el-col :span="12">
    <el-form-item label="序号" prop="id">
      <el-input v-model="insertUpd.id"></el-input>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="逻辑删除" prop="isDelete">
      <el-input v-model="insertUpd.isDelete"></el-input>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="创建时间" prop="OperationTime">
      <el-input v-model="insertUpd.OperationTime"></el-input>
    </el-form-item>
  </el-col>
  <el-col :span="12">
    <el-form-item label="创建人" prop="Operator">
      <el-input v-model="insertUpd.Operator"></el-input>
    </el-form-item>
  </el-col>
</el-row>
    <el-row>
  <el-col :span="12">
      <span class="xins">*</span><el-form-item label="上级分类">
        <el-cascader v-model="insertUpd.SjType"
        :options="options"
        :props="{ checkStrictly:true }"
        v-on:change="handleCascaderChange">
      </el-cascader>
      </el-form-item>
      </el-col>
      <el-col :span="12">
        <span class="xin">*</span><el-form-item label="货品类型编号" prop="Code">
          <el-input v-model="insertUpd.Code"></el-input>
        </el-form-item>
    </el-col>
  </el-row>
    <el-row>
      <el-col :span="12">
        <span class="xin">*</span><el-form-item label="货品类型名称" prop="Name">
          <el-input v-model="insertUpd.Name"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12" class="xinx">
        <el-form-item label="排序" prop="Sort">
          <el-input v-model="insertUpd.Sort"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
<el-col :span="12">
  <el-form-item label="状态" prop="Status">
    <el-radio-group v-model="insertUpd.Status">
      <el-radio :label="true">启用</el-radio>
      <el-radio :label="false">停用</el-radio>
    </el-radio-group>
  </el-form-item>
</el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="备注" prop="Remarks">
          <el-input type="textarea" v-model="insertUpd.Remarks" :rows="4"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row justify="end">
      <el-col>
        <el-button class="cz" @click="cancel()">取消</el-button>
        <el-button class="cx" @click="updFrom('insertFrom')">保存</el-button>
      </el-col>
    </el-row>
  </el-form>
</el-dialog>
    </div>
</template>

<script>
import axios from 'axios';
export default {
    data(){
        return{
            data:[
                { p_ProductTypeStatus: true },
                { p_ProductTypeStatus: false },
            ],
            options: [],//级联
            //编号
     orderNumber:'',
            value: "",
            insert:false,
            uinsert:false,
            showIdInput: false,
            targetPage: "",
            totalRecords: 10,
            currentPage: 1,
            totalPages: 10,
            pageSize: 10,
            search:{
                Key:'',
                Status:'',
                Operator:'',
                OperationTime:'',
            },
             insertAdd:{
                SjType:"",
                Code:"",
                Name:"",
                Sort:"",
                Status:true,
                Remarks:"",
            },
            insertUpd:{
                id:0,
                OperationTime:"",
                Operator:"",
                isDelete:"",
                SjType:"",
                Code:"",
                Name:"",
                Sort:"",
                Status:"",
                Remarks:"",
            },
}
},
 methods: {
  generateCode() {
      // 生成随机大写字母
      const randomLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));

      // 生成当前日期
      const currentDate = new Date().toISOString().slice(0, 10).replace(/-/g, '');

      // 生成4个随机数字
      const randomDigits = Math.floor(1000 + Math.random() * 9000);

      // 组合成编号
      return randomLetter + currentDate + randomDigits;
    },
            //查询
        fill(){
        axios.get('http://localhost:5084/api/ProductType/FenYe',{
            params: {
            pageSize: this.pageSize,
            currentPage: this.currentPage
       }
        })
          .then(res => {
            this.data = res.data;
            this.totalRecords = res.data.length;
            this.totalPages = Math.ceil(this.totalRecords / this.pageSize); // 计算总页数
          })
       },
       //模糊查询
      query() {
  // 查询数据逻辑
  const { Key, Status,Operator,OperationTime } = this.search;

  // 将状态值转换为布尔类型
  let statusValue;
  if (Status === 'true') {
    statusValue = true;
  } else if (Status === 'false') {
    statusValue = false;
  }

  axios.get('http://localhost:5084/api/ProductType/FenYe', {
    params: {
      pageSize: this.pageSize,
      currentPage: this.currentPage,
      Key: Key,
      Status: statusValue,
      Operator: Operator,
      OperationTime: OperationTime,
    } 
  }).then((response) => {
    this.data = response.data;
  }).catch((error) => {
    console.log(error);
  });
},
//添加
 addFrom(insertFrom) {
    var t = this;
   this.orderNumber = this.generateCode();
    this.$refs[insertFrom].validate((valid) => {
      if (valid) {
        axios
          .post("http://localhost:5084/api/ProductType", {
            p_ProductTypePid: t.insertAdd.SjType ? t.insertAdd.SjType : 0,
            p_ProductTypeCode:this.orderNumber,
            p_ProductTypeName: t.insertAdd.Name,
            p_ProductTypeSorting: t.insertAdd.Sort,
            p_ProductTypeStatus: t.insertAdd.Status,
            p_ProductTypeDescr:t.insertAdd.Remarks,
          })
          .then(res => {
            if (res) {
              this.$message({
                message: '添加成功！',
                type: 'success'
              });
              this.insert = false;
              t.fill();
                 // 清空表单数据
            this.insertAdd.SjType = '';
             this.insertAdd.Name = '';
            this.insertAdd.Code = '';
            this.insertAdd.Sort = '';
            this.insertAdd.Remarks = '';
            }
          })
          .catch(err => {
            this.$message({
              message: '添加失败！',
              type: 'error'
            });
          });
      }
    });
  },
  upd(row){
  this.uinsert = true;
  this.Yiji();

  this.insertUpd.id=row.p_ProductTypeId;
  this.insertUpd.Name=row.p_ProductTypeName;
  this.insertUpd.Sort=row.p_ProductTypeSorting;
  this.insertUpd.Status=row.p_ProductTypeStatus;
  this.insertUpd.isDelete=row.p_PIsDelete;
  this.insertUpd.OperationTime=row.p_ProductTypeOperationTime;
  this.insertUpd.Operator=row.p_ProductTypeOperator;
  this.insertUpd.Code=row.p_ProductTypeCode;
  this.insertUpd.SjType=row.p_ProductTypePid;
  this.insertUpd.Remarks=row.p_ProductTypeDescr;
},
//修改
updFrom: function () {
  var t = this;
  var tt={
    p_ProductTypeCode: t.insertUpd.Code,
    p_ProductTypeName:t.insertUpd.Name,
    p_ProductTypeSorting: t.insertUpd.Sort,
    p_ProductTypeStatus: t.insertUpd.Status,   
    p_ProductTypeOperationTime: t.insertUpd.OperationTime,
    p_ProductTypeOperator: t.insertUpd.Operator,
    p_ProductTypePid: t.insertUpd.SjType,
    p_ProductTypeDescr: t.insertUpd.Remarks,
    p_PIsDelete: t.insertUpd.isDelete,
  };
  // 调用修改接口，将this.xxx作为请求的数据发送给后端
  axios.put("http://localhost:5084/api/ProductType",{
    p_ProductTypeId:t.insertUpd.id,
    p_ProductTypeCode: t.insertUpd.Code,
    p_ProductTypeName:t.insertUpd.Name,
    p_ProductTypeSorting: t.insertUpd.Sort,
    p_ProductTypeStatus: t.insertUpd.Status,   
    p_ProductTypeOperationTime: t.insertUpd.OperationTime,
    p_ProductTypeOperator: t.insertUpd.Operator,
    p_ProductTypePid: t.insertUpd.SjType ? t.insertUpd.SjType : 0,
    p_ProductTypeDescr: t.insertUpd.Remarks,
    p_PIsDelete: t.insertUpd.isDelete,
  })
    .then(res => {
      if (res) {
        this.$message({
          message: '修改成功！',
          type: 'success'
        });
        this.uinsert = false; // 关闭修改页面
        t.fill(); // 重新填充销售机会列表
      }
    })
    .catch(err => {
      this.$message({
        message: '修改失败！',
        type: 'error'
      });
      console.info(tt);
    });
},
  //点击按钮删除
  del: function (sale) {
    if (confirm("确定删除吗")) {
        var t = this;
        axios.put(`http://localhost:5084/api/ProductType/UpdIsDelete?id=${sale.p_ProductTypeId}&&isDeleted=${false}`)
            .then(function (response) {
                // 根据后台返回的结果处理相应逻辑
                if (response.data > 0) {
                    alert("删除成功");
                    t.fill(); // 如果删除成功，重新加载数据
                } else {
                    alert("删除失败");
                }
            })
            .catch(function (error) {
                console.error(error);
                alert("删除失败");
            });
    }
},
handleCascaderChange(value) {
        // 获取选中的 value 和 label
    const selectedValue = value[value.length - 1];
    const selectedLabel = this.getLabelByValue(selectedValue);
    this.insertAdd.SjType = selectedValue.toString();
    // 打印选中的 value 和 label
    console.log('选中的 label 的值:', selectedLabel);
    console.log('选中的 value 的值:', selectedValue);
  },
  getLabelByValue(value) {
    // 在 options 中查找对应 value 的 label
    const findLabel = (options, value) => {
      for (const item of options) {
        if (item.value === value) {
          return item.label;
        }
        if (item.children) {
          const label = findLabel(item.children, value);
          if (label) {
            return label;
          }
        }
      }
      return null;
    };
    
    return findLabel(this.options, value);
    },
  //一级下拉
Yiji() {
				axios.get("http://localhost:5084/api/ProductType")
					.then((response) => {
						this.options = response.data.map(item => {
							return {
								value: item.value,
								label: item.label,
								children: item.children
							};
						});
            console.log('获取到的数据:', this.options); // 打印获取到的数据
					})
					.catch((error) => {
						console.log(error);
					});
},
 //点击新增显示弹框
add() {
  this.insert = true;
  this.Yiji();
},
//点击关闭弹框
cancel() {
  this.insert = false;
  this.uinsert = false;
},
       //重置按钮实现
  clear() {
    // 清空搜索条件
  this.search.Key = '';
  this.search.Status = '';
  this.search.Operator = '';
  this.search.OperationTime = '';
  // 重新调用查询方法，以获取所有数据
  this.fill();
  },
  handleSizeChange: function (size) {
				console.log(size);
				this.pageSize = size;
				this.fill();
  },
  handleCurrentChange: function (cpage) {
				console.log(cpage);
				this.currentPage = cpage;
				this.fill();
    },
    formatStatus(row, column, cellValue) {
                return cellValue ? '启用' : '停用';
                },
       },
       mounted: function () {
    this.fill();
 }
}
</script>

<style scoped>
.cz
{
margin-right: 20px; 
width: 80px; 
height: 40px; 
background-color: white; 
color: black;
border-color: #C1C1C1;
margin-left: 20px;
}
.cx
{
   width: 80px;
   height: 40px; 
   color: white;
   background-color: #45B984; 
}
.bian
{
    margin:20px;
}
 .el-dialog {
    max-height: 70%;
  }
  .xin{
  white:1px;
  height:1px;
  color: red;
  position: relative;
  left: -5px; /* 根据需要调整星号的水平位置 */
  top: 32px; /* 根据需要调整星号的垂直位置 */
}
.xinx{
    white:1px;
  height:1px;
  color: red;
  position: relative;
  left: 0px; /* 根据需要调整星号的水平位置 */
  top: 20px; /* 根据需要调整星号的垂直位置 */
}
.xins{
    white:1px;
  height:1px;
  color: red;
  position: relative;
  left: 20px; /* 根据需要调整星号的水平位置 */
  top: 32px; /* 根据需要调整星号的垂直位置 */
}
.xi{
  color: red;
  position: relative;
  left: 0px; /* 根据需要调整星号的水平位置 */
  top: 20px; /* 根据需要调整星号的垂直位置 */
}
</style>